package com.bluefoxyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bluefoxyu.domain.entity.Course;
import com.bluefoxyu.domain.entity.Enrollment;
import com.bluefoxyu.domain.entity.Teacher;
import com.bluefoxyu.domain.vo.JobTitleStatistics;
import com.bluefoxyu.domain.vo.TeacherVO;
import com.bluefoxyu.mapper.CourseMapper;
import com.bluefoxyu.mapper.EnrollmentMapper;
import com.bluefoxyu.mapper.TeacherMapper;
import com.bluefoxyu.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.List;


/**
 * <p>
 * 教师信息表 服务实现类
 * </p>
 *
 * @author bluefoxyu
 * @since 2024-06-16
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {

    @Resource
    private TeacherMapper teacherMapper;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private EnrollmentMapper enrollmentMapper;

    // 统计不同职称的教师的数量、不同职称的教师的平均工资
    @Override
    public TeacherVO statistics() {
        // 调用自定义的Mapper方法来执行分组查询
        List<JobTitleStatistics> jobTitleStatistics = teacherMapper.selectStatistics();

        // 封装返回结果
        return TeacherVO.builder()
                .jobTitleStatistics(jobTitleStatistics)
                .build();
    }

    @Override
    public void deleteTeacher(Long teacherId) {

        // 先删除对应课程信息
        QueryWrapper<Course>CourseWrapper=new QueryWrapper<>();
        CourseWrapper.lambda().eq(Course::getTeacherId,teacherId);
        List<Course> courseList = courseMapper.selectList(CourseWrapper);
        
        //删除对应成绩表
        //检查该课程是否有成绩表
        if (!courseList.isEmpty()){
            //由于课程集合中课程id都一样，取第一个集合中数据的id即可
            Integer id = courseList.get(0).getId();
            QueryWrapper<Enrollment> enrollmentWrapper=new QueryWrapper<>();
            enrollmentWrapper.lambda().eq(Enrollment::getCourseId,id);
            enrollmentMapper.delete(enrollmentWrapper);
        }

        courseMapper.delete(CourseWrapper);

        // 删除教师信息
        teacherMapper.deleteById(teacherId);
    }

}
